package com.cn.jinl.service;

import com.cn.jinl.api.IChenxingMachineService;
import com.cn.jinl.api.IDeviceService;
import com.cn.jinl.api.ILineOtherService;
import com.cn.jinl.api.IOnDutyProductService;
import com.cn.jinl.dao.DeviceMapper;
import com.cn.jinl.dao.RepairReportMapper;
import com.cn.jinl.domain.*;
import com.cn.jinl.utils.CollectionsUtil;
import com.cn.jinl.utils.CommonUtil;
import com.cn.jinl.utils.Constants;
import com.cn.jinl.utils.QueryForm;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created On : 2023/12/11.
 * <p>
 * Author : Huiyan
 * <p>
 * Description: DeviceServiceImpl
 */
@Service
public class DeviceServiceImpl implements IDeviceService {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private ILineOtherService lineOtherService;

    @Autowired
    private RepairReportMapper repairReportMapper;

    @Autowired
    private IChenxingMachineService chenxingMachineService;

    @Autowired
    private IOnDutyProductService onDutyProductService;

    @Override
    public List<Device> getDeviceSelect(QueryForm queryForm) throws Exception {
        List<Device> list = deviceMapper.selectDeviceList(queryForm);
        return list;
    }

    @Override
    public List<Device> getDeviceGuanHao(String deviceCode) throws Exception {
        return deviceMapper.selectGuanHaoDevice(deviceCode);
    }

    @Override
    public String updateDevice(Device device) throws Exception {
        String id = device.getId();
        if (StringUtils.isEmpty(id)){
            return "id is null";
        }

        String result = this.deviceLegal(device);
        if (!"".equals(result)){
            return result;
        }

        if (this.countDeviceCode(device.getDeviceCode(),id) > 0){
            return "设备号已存在！";
        }

        DeviceExample example = new DeviceExample();
        example.createCriteria().andIdEqualTo(id).andStatusEqualTo(Constants.NORMAL_STATUS);

        int count = deviceMapper.updateByExampleSelective(device,example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String deleteDevice(QueryForm queryForm) throws Exception {

        List<String> ids = queryForm.getIds();
        if (CollectionsUtil.isEmpty(ids)){
            return "请选中要删除的设备！";
        }
        //TODO 设备表可能关联其他表，判断是否可以删除

        Device device = new Device();
        device.setStatus(Constants.DEL_STATUS);
        DeviceExample example = new DeviceExample();
        example.createCriteria().andIdIn(ids);
        int count = deviceMapper.updateByExampleSelective(device,example);

        return CommonUtil.outStr(count);
    }

    @Override
    public String addDevice(List<Device> devices) throws Exception {
        if (CollectionsUtil.isEmpty(devices)){
            return "请添加设备数据";
        }

        List<String> deviceCodes = Lists.newArrayList();
        for (Device device:devices){
            String result = this.deviceLegal(device);

            if (!"".equals(result)){
                return result;
            }

            String deviceId = CommonUtil.generateRandomNum("device_");
            device.setId(deviceId);
            device.setStatus(Constants.NORMAL_STATUS);

            deviceCodes.add(device.getDeviceCode());
        }

        DeviceExample example = new DeviceExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andDeviceCodeIn(deviceCodes);
        int existsCount = deviceMapper.countByExample(example);
        if (existsCount > 0){
            return "设备号已存在！";
        }
        int count = deviceMapper.batchInsertDevices(devices);

        return CommonUtil.outStr(count);
    }

    @Override
    public Map<String, List<String>> getDeviceByProcName(String processName,String processCategory) throws Exception {
        DeviceExample example = new DeviceExample();
        DeviceExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(Constants.NORMAL_STATUS);
        if(StringUtils.isNotEmpty(processName)){
            criteria.andProcessNameEqualTo(processName);
        }
        if(StringUtils.isNotEmpty(processCategory)){
            criteria.andProcessCategoryEqualTo(processCategory);
        }
        example.setOrderByClause("device_code asc");
        Map<String,List<String>> deviceMaps = Maps.newHashMap();
        List<Device> devices = deviceMapper.selectByExample(example);
        for(Device device:devices){
            if(deviceMaps.containsKey(device.getProcessCategory())){
                List<String> exist = deviceMaps.get(device.getProcessCategory());
                exist.add(device.getDeviceCode());
            }else {
                List<String> add = Lists.newArrayList();
                add.add(device.getDeviceCode());
                deviceMaps.put(device.getProcessCategory(),add);
            }
        }
        return deviceMaps;
    }

    @Override
    public Map<String, Map<String, List<String>>> getAllDeviceGroupByProcessName() throws Exception {
        DeviceExample example = new DeviceExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS);
        example.setOrderByClause("device_code asc");
        List<Device> devices = deviceMapper.selectByExample(example);
        Map<String, Map<String, List<String>>> resultMaps =  Maps.newHashMap();
        for(Device device :devices){
            if(resultMaps.containsKey(device.getProcessName())){
                Map<String,List<String>> existMap = resultMaps.get(device.getProcessName());
                if(existMap.containsKey(device.getProcessCategory())){
                    List<String> exist = existMap.get(device.getProcessCategory());
                    exist.add(device.getDeviceCode());
                }else{
                    List<String> add = Lists.newArrayList();
                    add.add(device.getDeviceCode());
                    existMap.put(device.getProcessCategory(),add);
                }
            }else {
                Map<String,List<String>> tempMap = Maps.newHashMap();
                List<String> add = Lists.newArrayList();
                add.add(device.getDeviceCode());
                tempMap.put(device.getProcessCategory(),add);
                resultMaps.put(device.getProcessName(),tempMap);
            }
        }
        return resultMaps;
    }

    @Override
    public Device getDeviceInfoByCode(String deviceCode) throws Exception {
        DeviceExample example = new DeviceExample();
        example.createCriteria().andDeviceCodeEqualTo(deviceCode).andStatusEqualTo(Constants.NORMAL_STATUS);
        List<Device> devices = deviceMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(devices)||devices.size() > 1){
            return null;
        }
        return devices.get(0);
    }

    @Override
    public Map<String,Object>  getOnDutyDeviceInfoByCode(String deviceCode) throws Exception {
        Map<String, Object> resultMap = Maps.newHashMap();
        Device device = this.getDeviceInfoByCode(deviceCode);
        if (null == device) {
            resultMap.put("error", "未查询到设备["+deviceCode+"]");
            return resultMap;
        }
        if(StringUtils.equals(device.getDeviceStatus(),"1")){
            resultMap.put("error", "设备已经停用！");
            return resultMap;
        }
        String processName = device.getProcessName();
        if(StringUtils.equals(processName, "成型")){
            ChenxingMachine chenxingMachine = chenxingMachineService.getChenxingMachineByDeviceCode(deviceCode);
            if (null == chenxingMachine ) {
                resultMap.put("error", deviceCode + "设备未查询到任务！");
                return resultMap;
            }
            if(!StringUtils.equals(chenxingMachine.getQjStatus(), "1")){
                resultMap.put("error", deviceCode + "设备未启动检验！");
                return resultMap;
            }
            device.setGradeValue(chenxingMachine.getGradeValue());
            device.setPlanName(chenxingMachine.getPlanName());
        }else if(StringUtils.equals(processName, "挤塑直切")){
            LineOther lineOther = lineOtherService.getOnDutyLineOtherByDeviceCode(deviceCode);
            if (null == lineOther) {
                resultMap.put("error", deviceCode + "设备未查询到任务！");
                return resultMap;
            }
            if(!StringUtils.equals(lineOther.getLineStatus(),"1")){
                resultMap.put("error", deviceCode +"设备未开机！");
                return resultMap;
            }
            device.setGradeValue(lineOther.getGradeValue());
            device.setPlanName(lineOther.getPlanName());
        }else {
            OnDutyProduct onDutyProduct = onDutyProductService.getScanOnDutyProductByDeviceCode(deviceCode);
            if (null == onDutyProduct) {
                resultMap.put("error", "未查询到设备！");
                return resultMap;
            }
            if(!StringUtils.equals(onDutyProduct.getProductStatus(),"2")){
                resultMap.put("error", deviceCode +"设备未开机！");
                return resultMap;
            }
            device.setGradeValue(onDutyProduct.getGradeValue());
            device.setPlanName(onDutyProduct.getPlanName());
        }
        resultMap.put("device", device);
        return resultMap;
    }

    @Override
    public Map<String, String> getDeviceCodeItemName() throws Exception {
        DeviceExample example = new DeviceExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS);
        List<Device> devices = deviceMapper.selectByExample(example);
        Map<String,String>deviceMap = Maps.newHashMap();
        for(Device device :devices){
            deviceMap.put(device.getDeviceCode(),device.getProcessName());
        }
        return deviceMap;
    }

    @Override
    public DeviceReportVo getDeviceReportByCode(String deviceCode) {
        DeviceReportVo deviceReportVo = new DeviceReportVo();
        DeviceExample example = new DeviceExample();
        example.createCriteria().andDeviceCodeEqualTo(deviceCode).andStatusEqualTo(Constants.NORMAL_STATUS);
        List<Device> devices = deviceMapper.selectByExample(example);
        deviceReportVo.setDeviceCode(devices.get(0).getDeviceCode());
        deviceReportVo.setDeviceName(devices.get(0).getDeviceName());
        deviceReportVo.setProcessName(devices.get(0).getProcessName());
        deviceReportVo.setProcessCategory(devices.get(0).getProcessCategory());
        deviceReportVo.setDeviceStatus(devices.get(0).getDeviceStatus());
        if(CollectionUtils.isEmpty(devices)||devices.size() > 1){
            return null;
        }
        if (devices.size()>0){
            for (Device device : devices){
                String str=device.getProcessName()+"/"+device.getProcessCategory();
                RepairReportExample reportExample = new RepairReportExample();
                reportExample.createCriteria().andProceduresEqualTo(str).andEquipmentNameEqualTo(device.getDeviceName()).andEquipmentNumberEqualTo(device.getDeviceCode()).andStatusEqualTo("0");
                List<RepairReport> repairReports = repairReportMapper.selectByExample(reportExample);
                if (repairReports.size()>0){
                    deviceReportVo.setReportingTime(repairReports.get(0).getReportingTime());
                    deviceReportVo.setRepairName(repairReports.get(0).getRepairName());
                    deviceReportVo.setFaultDescription(repairReports.get(0).getFaultDescription());
                    deviceReportVo.setId(repairReports.get(0).getId());
                }else {
                    return null;
                }

            }
        }

        return deviceReportVo;
    }


    private int countDeviceCode(String code,String id){
        DeviceExample example = new DeviceExample();
        DeviceExample.Criteria criteria = example.createCriteria();

        criteria.andStatusEqualTo(Constants.NORMAL_STATUS).andDeviceCodeEqualTo(code);
        if (StringUtils.isNotEmpty(id)){
            criteria.andIdNotEqualTo(id);
        }

        int count = deviceMapper.countByExample(example);
        return count;
    }

    private String deviceLegal(Device device){

        String result = "";

        if (StringUtils.isBlank(device.getProcessName())){
            result = "请选择工段名称";
            return result;
        }
        if (StringUtils.isBlank(device.getProcessCategory())){
            result = "请选择工序名称";
            return result;
        }
        if (StringUtils.isBlank(device.getDeviceCode())){
            result = "请填写设备号";
            return result;
        }
        if (StringUtils.isBlank(device.getDeviceName())){
            result = "请填写设备名称";
            return result;
        }
        if (StringUtils.isBlank(device.getDeviceStatus())){
            result = "请选择设备状态";
            return result;
        }

        return result;
    }


}
